/**
 * Created by FreezeSoul on 2016/5/17.
 */
define([
        'angular',
        'adConfig',
        'app/modules/import/define',
        'app/modules/import/services/import'
    ],
    function (angular, adConfig) {
        angular.module('ad.import')
            .controller('adImportController', ['$rootScope', '$scope', '$state', 'Notification', 'FileUploader', 'adImportService',
                function ($rootScope, $scope, $state, Notification, FileUploader, service) {

                    $scope.actionState = 0;

                    $scope.schameId = 0;
                    $scope.dataSetId = 0;

                    var fileSupports = ['xlsx'];
                    $scope.supportsArray = fileSupports;

                    $scope.uploader = new FileUploader();
                    $scope.uploader.queueLimit = 1;
                    $scope.uploader.removeAfterUpload = true;
                    $scope.uploader.url = adConfig.baseServiceUrl + 'common/excel/upload';
                    $scope.uploader.headers = {
                        'Authorization': 'Bearer ' + $rootScope.currentUser.UserToken
                    };

                    $scope.uploader.filters.push({
                        name: 'fileName',
                        fn: function (item) {
                            var fileExtension = item.name.split('.').pop();
                            return fileSupports.indexOf(fileExtension.toLowerCase()) > -1;
                        }
                    });

                    $scope.uploader.onAfterAddingFile = function () {
                        angular.element("#excel-upload").val(null);
                        $scope.actionState = 0;
                        $scope.schameId = 0;
                        $scope.dataSetId = 0;
                    };

                    $scope.uploader.onCompleteItem = function (item, response, status, headers) {
                        if (response.result == "success") {
                            $scope.schameId = response.data.schemaId;
                            $scope.dataSetId = response.data.dataSetId;
                        }
                    };

                    $scope.uploader.onCompleteAll = function () {
                        $scope.actionState = 2;
                    };

                    $scope.uploadExcel = function () {
                        $scope.actionState = 1;
                        $scope.uploader.uploadAll();
                    };

                    $scope.navigateToDataset = function ($event) {
                        $state.go('editor.schema.dataset-edit', {
                            schemaid: $scope.schameId,
                            datasetid: $scope.dataSetId
                        });
                        $event.preventDefault();
                    };
                }]);
    });